package com.xcw.globalException;

import cn.hutool.json.JSONUtil;
import com.xcw.base.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author bhx
 * @Date 2022/8/21 22:02
 * @Description 全局异常处理器
 */
@Slf4j
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        // 参数异常+ 无效状态异常
        if (ex instanceof IllegalArgumentException || ex instanceof IllegalStateException){
            log.error(ex.getMessage());
        } else {
            log.error(ex.getMessage(),ex);
        }
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        if ("XXLHttpRequest".equals(requestType)){
            try {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().println(JSONUtil.toJsonStr(Result.fail(ex.getMessage())));
            } catch (IOException e) {
                //TODO
            }
            return new ModelAndView();
        } else {
            httpServletRequest.setAttribute("message","系统异常，请稍后再试！");
        }
        return new ModelAndView("error");
    }
}
